package com.cn.fangshuo.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cn.fangshuo.entity.CarWash;
import com.cn.fangshuo.enums.RedisKeyEnum;
import com.cn.fangshuo.service.ICarWashService;
import com.cn.fangshuo.util.RedisUtil;
import com.cn.fangshuo.util.StrUtil;
import com.cn.fangshuo.util.TimeUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Component
public class PushWuXiDaYunCarWashTask {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICarWashService carWashService;

    private final String deviceUuid = "YYCC1000001063";

    private final String baseURL = "https://gd.jsdayun.cn:9913/Api";

    private final String appId = "sys379ce32f719424a2";

    private final String secret = "3d7dce0cbba2bd4e";

    private final String aesSecret = "e28c82dd18cbd3de";

    private final AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, aesSecret.getBytes(StandardCharsets.UTF_8));

    public String getToken(){
        String pass = aes.encryptBase64(String.format("%s:%s", secret, System.currentTimeMillis()));
        try (HttpResponse response = HttpRequest.post(baseURL + "/rest/Token/get/" + appId + "/").form("pass", pass).execute()){
            if (!response.isOk()){
                return null;
            }
            JSONObject result = JSONObject.parseObject(response.body());
            log.info("获取token结果：{}", result);
            if (!"0000".equals(result.getString("flag"))){
                return null;
            }
            return result.getJSONObject("result").getString("access_token");
        }
    }

    public String getSign(JSONObject jsonObject, String token){
        // 使用TreeMap自动按key排序
        Map<String, Object> sortedMap = new TreeMap<>(jsonObject);
        // 拼接所有value
        StringBuilder concatenated = new StringBuilder();
        for (String key : sortedMap.keySet()) {
            concatenated.append(sortedMap.get(key));
        }
        concatenated.append(token);
        log.info("待签名字符串：{}", concatenated);
        return SecureUtil.sha256(concatenated.toString());
    }

    public void push() {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime;
        String lastCarWashPushTime = redisUtil.getString(RedisKeyEnum.LAST_CAR_WASH_PUSH_TIME.getKey() + deviceUuid);
        if (StrUtil.isBlank(lastCarWashPushTime)){
            startTime = LocalDateTime.now().minusMinutes(5);
        } else {
            startTime = TimeUtil.parseLocalDateTime(lastCarWashPushTime);
        }
        List<CarWash> list = carWashService.list(new LambdaQueryWrapper<CarWash>().ge(CarWash::getCreateTime, startTime).lt(CarWash::getCreateTime, endTime).eq(CarWash::getDeviceUuid, deviceUuid));
        if (CollUtil.isNotEmpty(list)){
            log.info("==========推送无锡大运车冲信息开始：{}====================", TimeUtil.format(endTime));
            String token = getToken();
            if (token == null){
                token = getToken();
            }
            if (token != null){
                for (CarWash carWash : list) {

                }
            }
        }
    }

    @SneakyThrows
    public String install(){
        String token = getToken();
        while (token == null){
            Thread.sleep(1000L * 5);
            token = getToken();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceId", deviceUuid);
        jsonObject.put("deviceName", "工地门口");
        jsonObject.put("installTime", "2024-07-17");
        String sign = getSign(jsonObject, token);
        try (HttpResponse response = HttpRequest.post(baseURL + "/rest/CarWash/Info/" + appId + "/" + sign).execute()){
            if (!response.isOk()){
                return null;
            }
            JSONObject result = JSONObject.parseObject(response.body());
            log.info("获取token结果：{}", result);
            return result.toJSONString();
        }
    }

    public static class PushInfo {

        private String deviceId;//设备ID

        private String carNo;//车牌号

        private String carType;//车类型: 1:渣土车，2:其他

        private String carPlateColor;//车牌颜色：0:蓝，1:黄，2:绿

        private String event;//冲洗事件：0:前进冲洗，1:前进绕道，2:倒车绕道，3:倒车冲洗

        private String washTotalDuration;//冲洗时长，单位（秒)

        private String washTime;//冲洗时间，字符串时间格式，yyyy-mm-dd hh:mi:ss.(2022-05-06 15:05:02),24小时制

        private String images;//抓拍图片列表,多个图片用逗号分隔

        private String videoUrl;//录像url
    }

}
